package org.xobo.finance.helper.invoice.service.impl;

import java.util.List;

import javax.persistence.EntityManager;

import org.malagu.panda.dorado.linq.JpaUtil;
import org.malagu.panda.importer.policy.Context;
import org.malagu.panda.importer.policy.PostProcessPolicy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.xobo.finance.helper.invoice.entity.Invoice;
import org.xobo.finance.helper.invoice.service.InvoiceService;

@Service
public class InvoicePostProcessPolicy implements PostProcessPolicy {
  final public static String BEAN_ID = "importer.defaultPostProcessPolicy";
  private String beanName;

  @Override
  public void apply(Context context) throws Exception {
    List<Object> resultList = context.getResultList();
    int i = 0;
    for (Object entity : resultList) {
      if (!(entity instanceof Invoice)) {
        continue;
      }
      Invoice invoice = (Invoice) entity;
      String invoiceNo = invoice.getInvoiceNo();
      String invoiceCode = invoice.getInvoiceCode();
      Long invoiceId = invoiceService.findInvoiceId(invoiceCode, invoiceNo);
      if (invoiceId != null) {
        invoice.setId(invoiceId);
        JpaUtil.merge(invoice);
      } else {
        JpaUtil.persist(invoice);
      }
      if (i++ % 100 == 0) {
        EntityManager entityManager = JpaUtil.getEntityManager(entity);
        entityManager.flush();
        entityManager.clear();
      }
    }

  }


  @Override
  public String getCaption() {
    return "保存发票导入";
  }


  @Override
  public void setBeanName(String name) {
    beanName = name;
  }


  public String getBeanName() {
    return beanName;
  }

  @Autowired
  private InvoiceService invoiceService;

}
